package com.itheima.zzyl.controller;

import com.itheima.zzyl.pojo.PageResult;
import com.itheima.zzyl.pojo.Reservation;
import com.itheima.zzyl.pojo.Result;
import com.itheima.zzyl.service.ReservationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/reservation")
public class ReservationController {

    @Autowired
    @Qualifier(value = "reservationService")
    private ReservationService reservationService;

    @Cacheable(value = "reservationCache", key = "#userId+'_'+#pageSize+'_'+#pageNum")
    @GetMapping("/page")
    public Result<PageResult<Reservation>> page(
            @RequestParam("userId") Integer userId,
            @RequestParam("pageSize") Integer pageSize,
            @RequestParam("pageNum") Integer pageNum,
            @RequestParam(value = "status", required = false) Integer status
    ) {
        return reservationService.page(pageSize, pageNum, status);
    }


    @CacheEvict(value = "reservationCache", allEntries = true)
    @PostMapping
    public Result<Object> addReservation(
            @RequestBody Reservation reservation,
            @RequestParam("userId") Integer userId
    ) {
        reservation.setCreateTime(LocalDateTime.now());
        if (userId == null) {
            return Result.error("用户id不能为空");
        }
        reservationService.addReservation(reservation);
        return Result.success("操作成功");
    }


    @PutMapping("/{id}/cancel")
    public Result<Object> cancelReservation(
            @PathVariable Integer id
    ) {
        if (id == null) {
            return Result.error("id不能为空");
        }
        reservationService.updateReservationStatus(id);
        return Result.success("操作成功");
    }

}
